package com.vincce.fitness.core.util;

import com.thoughtworks.xstream.XStream;
import com.vincce.fitness.api.WechatRunner;
import com.vincce.fitness.constant.WechatConstant;
import com.vincce.fitness.entity.Account;
import com.vincce.fitness.entity.WechatMessage;
import org.apache.http.client.fluent.Executor;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.ContentType;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * User: henry
 * Date: 8/16/13
 * Time: 3:37 PM
 * To change this template use File | Settings | File Templates.
 */
public class WechatUtil {

	public static boolean checkSignature(String signature, String timestamp, String nonce, String echoStr) {
		String[] ss = new String[] {WechatConstant.TOKEN, timestamp, nonce };
		Arrays.sort(ss);
		String content = StringUtils.arrayToDelimitedString(ss, "");

		try {
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			byte[] digest = md.digest(content.getBytes());
			StringBuilder sb = new StringBuilder();
			for (byte b : digest) {
				sb.append(String.format("%02X", b));
			}
			if (sb.toString().equals(signature.toUpperCase())) {
				return true;
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return false;
	}

	private static XStream genXStream(WechatMessage message) {
		XStream xStream = new XStream(new CDataXppDriver("utf-8"));
		xStream.alias("xml", WechatMessage.class);
		xStream.aliasField("ToUserName", WechatMessage.class, "toUserName");
		xStream.aliasField("FromUserName", WechatMessage.class, "fromUserName");
		xStream.aliasField("CreateTime", WechatMessage.class, "createTime");
		xStream.aliasField("MsgType", WechatMessage.class, "msgType");
		xStream.aliasField("Content", WechatMessage.class, "content");
		xStream.aliasField("PicUrl", WechatMessage.class, "picUrl");
		xStream.aliasField("MsgId", WechatMessage.class, "msgId");
		xStream.aliasField("MediaId", WechatMessage.class, "mediaId");
		xStream.aliasField("Event", WechatMessage.class, "event");
		xStream.aliasField("EventKey", WechatMessage.class, "eventKey");
		xStream.aliasField("Format", WechatMessage.class, "format");
		xStream.aliasField("Recognition", WechatMessage.class, "recognition");
		xStream.aliasField("Ticket", WechatMessage.class, "ticket");
		xStream.aliasField("Latitude", WechatMessage.class, "latitude");
		xStream.aliasField("Longitude", WechatMessage.class, "longitude");
		xStream.aliasField("Precision", WechatMessage.class, "precision");
		xStream.aliasField("MsgID", WechatMessage.class, "msgID");
		xStream.aliasField("Status", WechatMessage.class, "status");
		if (message != null && message.getArticleCount() != null && message.getArticleCount() > 0) {
			xStream.aliasField("ArticleCount", WechatMessage.class, "articleCount");
			xStream.aliasField("Articles", WechatMessage.class, "articles");
			xStream.alias("item", WechatMessage.Article.class);
			xStream.aliasField("Title", WechatMessage.Article.class, "title");
			xStream.aliasField("Description", WechatMessage.Article.class, "description");
			xStream.aliasField("PicUrl", WechatMessage.Article.class, "picUrl");
			xStream.aliasField("Url", WechatMessage.Article.class, "url");
		}
		if (message != null && message.getMusic() != null) {
			xStream.alias("Music", WechatMessage.Music.class);
			xStream.aliasField("Title", WechatMessage.Music.class, "title");
			xStream.aliasField("Description", WechatMessage.Music.class, "description");
			xStream.aliasField("MusicUrl", WechatMessage.Music.class, "musicUrl");
			xStream.aliasField("HQMusicUrl", WechatMessage.Music.class, "hqMusicUrl");
		}
		return xStream;
	}

	public static WechatMessage xmlToMessage(String body) {
		System.out.println(body);
		return (WechatMessage) genXStream(null).fromXML(body, new WechatMessage());
	}

	public static String messageToXml(WechatMessage message) {
		String xml = genXStream(message).toXML(message);
		System.out.println(xml);
		return xml;
	}

	public static String generateOauthUrl(String url,Account account) throws UnsupportedEncodingException {
		String oauth_authorize_url =  String.format("%s/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_base&state=0#wechat_redirect", WechatConstant.OAUTH_URL_PREFIX,account.getAppId(),"%s");
		return String.format(oauth_authorize_url,URLEncoder.encode(url, "utf-8"));
	}

	public static class HttpUtil {
		public static String fetch(Request request, String bodyString) throws IOException {
			return fetch(request.bodyString(bodyString, ContentType.create("text/plain", "UTF-8")));
		}

		public static String fetch(Request request) throws IOException {
			Executor executor = Executor.newInstance();
			String result = executor.execute(request).returnContent().asString();
			executor.clearCookies();
			result = new String(result.getBytes("ISO8859-1"), "UTF-8");
			return result;
		}

		public static InputStream fetchInputStream(Request request) throws IOException {
			Executor executor = Executor.newInstance();
			InputStream is = executor.execute(request).returnContent().asStream();
			executor.clearCookies();
			return is;
		}


	}

}
